<template>
  <!--tab模块-->
  <view>
    <loading :showLoaded.sync="showLoaded"></loading>
    <navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
    <onlineService></onlineService>
    <view class="swiper-tab-pd">
      <superscript ref="tab" :currentTab="currentTab" v-bind:tabList="tabList" v-on:currentTab="getCurrentTab">
      </superscript>
    </view>
    <view class="swiper-item-box2">
      <block v-if="currentTab == 2 || currentTab == 3">
        <itemParse :identifier.sync="identifier" :preview.sync="preview"></itemParse>
      </block>
      <orderList v-show="!is_empty" ref="orderListRef" @skipPaySucc="skipPaySucc" :orderList="orderList"
        :orderStatusList="orderStatusList" :isRefundList.sync="isRefundList" @endCutdown='endCutdown'
        @getMyOrderSale='getMyOrderSale' @setOrderId='setOrderId' :showLoaded='showLoaded'></orderList>
    </view>
    <!--暂无数据显示-->
<!--    <placeholder :is_empty.sync="is_empty" :message="openAppointment && currentTab == 1 ? '您还没有预约单' : '您还没有订单'">
    </placeholder> -->
    <block v-if="is_empty">
      <view class="empty_cart">
        <image class="icon-xl" src="https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/cart/empty_cart_logo4x.png" />
        <view class="empty_cart_text">暂无订单记录</view>
        <view class="get_store" @click="handleToHomePage">前往首页</view>
      </view>
      <image class="empty_line" src="https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/cart/empty_cart_line3x.png"></image>
      <block v-if="cartRecommendShow">
        <utools-parse id="utools-parse-order-lists" page="order" @triggerComponent="onTriggerComponent" @setPanel="setPanel"
          :utools-data="cartRecommendUtools" @onAddCart="onAddCart"></utools-parse>
      </block>
    </block>
    <view class="ios_safe_zone" v-if="isIos">
      <view class="ios_safe_zone_line"></view>
    </view>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
  </view>
</template>
<script>
  import Superscript from './superscript';
  import {
    MERCHANT_INFO,
    CUSTOMER_INFO,
    SYSTEM_INFO
  } from '@/utils/constant';
  import OrderList from './orderList.vue';
  import LoadMore from '@/components/common/loadMore';
  import itemParse from '../../components/wxparse/wxparse';
  import Placeholder from '@/components/common/placeholder';
  import api from '@/api/api';
  import onlineService from '@/components/common/onlineService';
  import Loading from '@/components/common/loading';
  import NavBar from '../../components/common/navbar';
  export default {
    // config: {
    //   navigationBarTitleText: '我的订单',
    //   enablePullDownRefresh: true
    // },
    components: {
      onlineService: onlineService,
      superscript: Superscript,
      orderList: OrderList,
      loadMore: LoadMore,
      placeholder: Placeholder,
      loading: Loading,
      navBar: NavBar,
      itemParse: itemParse,
    },
    data() {
      return {
        navbarData: {
          showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
          navbarTitle: this.$programSetting.openAppointment ? "我的订单/预约申请" : "我的订单", //导航栏 中间的标题
          hideSearch: true,
          hideHome: false
        },
        openAppointment: this.$programSetting.openAppointment,
        isOrderStatusList: false, //是否显示顶部提醒
        identifier: 'cms/bannerTop', //cms
        preview: false,
        isShowCustomNavBar: true,
        showLoaded: false,
        back: '',
        winHeight: 0,
        cancelTime: "",
        tabList: ['全部订单', '待审核', '待支付', '待发货', '待收货', '待评价', '已完成'],
        orderStatusArr: ['WAIT_SYSTEM_CONFIRM', 'WAIT_BUYER_PAY', 'WAIT_SELLER_SEND_GOODS', 'WAIT_BUYER_CONFIRM_GOODS',
          'TRADE_FINISHED',
          'WAIT_EVALUATION'
        ],
        orderStatusList: {
          WAIT_SYSTEM_CONFIRM: '待审核',
          WAIT_BUYER_PAY: '待支付',
          BUYER_PART_PAYMENT: '待支付',
          WAIT_SELLER_SEND_GOODS: '待发货',
          WAIT_BUYER_CONFIRM_GOODS: '待收货',
          TRADE_FINISHED: '已完成',
          TRADE_CLOSED: '已取消',
          TRADE_CLOSED_BY_CLOUD: '已关闭',
          //退货单状态
          // WAIT_BUYER_RETURN_GOODS: '待退货',
          // WAIT_SELLER_AGREE: '待发货',
          // WAIT_BUYER_RETURN_GOODS: '待退货',
          // WAIT_SELLER_CONFIRM_GOODS: '待退款',
          CLOSED: '已关闭',
          SUCCESS: '退款成功',
          WAIT_EVALUATION: '待评价',
          RETAIL_STORE_RECEIVED: '门店已收货',
          DC_RECEIVED: '仓库已收货'
        },
        orderList: [],
        currentPage: 1,
        is_empty: false,
        orderStatus: '',
        currentTab: 0,
        flag: 0,
        //是否显示 底部loading
        showLoading: false,
        //防止重复加载
        preventRepeatReuqest: false,
        //全部订单
        totalCount: 0,
        systemConfirmCount: 0,
        //待支付
        pendingPayCount: 0,
        //待发货
        backrdersCount: 0,
        //待收货
        shippedCount: 0,
        //已完成
        radeFinishedCount: 0,
        //退款/售后
        refundsCount: 0,

        receiveFlg: 0,
        skipPaySuccess: true,

        //退货订单
        refundCount: 0,
        //显示退货列表
        isRefundList: 'N',
        height: 0,
        statusBarHeight: 0,
        titleBarHeight: 0,
        identifiers: 'cms/itemrecommend',
        backSuccess: false,
        nowPages: '',
        showSale: false,
        id: 'cms/speicalTip',
        isIpx: false,
        submitOrderId: '',
        cartRecommendShow: false,
        cartRecommendUtools: null, //  为你推荐 utools json
        utoolsClassGoodsLists: [],  //  utools分类商品集合数组
        isIos: false
      };
    },

    onLoad(opts) {
      this.handleUtoolsCartRecommend(opts);
      let pages = getCurrentPages();
      let prevpage = pages[pages.length - 2];
      var currPage = pages[pages.length - 1]; //当前页面
      this.nowPages = currPage.route;
      if (prevpage == undefined) {
        this.back = '';
      } else {
        this.back = prevpage.route ? prevpage.route : '';
      }
      let that = this;
      let title = '';
      that.orderList = [];
      that.currentTab = opts.type ? opts.type : 0;
      that.cancelTime = getApp().globalData.cancelTime * 60;
      // that.getMyOrder();
      //设置滚动高度
      let systemInfo = uni.getSystemInfoSync();
      let totalTopHeight = 76;
      if (systemInfo.model.indexOf('iPhone X') !== -1 || systemInfo.model.indexOf('iPhone1') !== -1) {
        totalTopHeight = 88;
      } else if (systemInfo.model.indexOf('iPhone') !== -1) {
        totalTopHeight = 64;
      }
      this.statusBarHeight = systemInfo.statusBarHeight || systemInfo.statusbarHeight;
      let statusBarHeight = systemInfo.statusBarHeight || systemInfo.statusbarHeight;
      this.height = totalTopHeight;
      this.titleBarHeight = totalTopHeight - statusBarHeight > 38 ? totalTopHeight - statusBarHeight : 38;
      that.winHeight = systemInfo.windowHeight;
      let isIpx = systemInfo.model.indexOf('iPhone X') !== -1 || systemInfo.model.indexOf('iPhone1') !== -1 ||
        systemInfo.model.indexOf('unknown<iPhone13') !== -1 || systemInfo.model.indexOf('iPhone 12/13') !== -1;
      this.isIpx = isIpx;

      this.isIos = 	wx.getSystemInfoSync().system.includes('iOS') && wx.getSystemInfoSync()?.safeArea?.top>20;
    },

    onShow() {
      let that = this;
      // 判断特殊购买的入口
      this.getMyOrderSale()
      this.$refs.orderListRef.setActive()
      if (this.backSuccess && this.currentTab !== 0 && this.currentTab !== 1) {
        that.orderList = []
        that.currentPage = 1
        let cur = that.currentTab
        that.getMyOrder(that.currentPage, 5, true, cur)
      }
      if (this.currentTab == 0 || this.currentTab == 1) {
        that.orderList = []
        that.currentPage = 1
        let cur = that.currentTab
        that.getMyOrder(1, 5, true, cur)
        if (!!this.submitOrderId) {
          this.getOrderInfo()
        }
      }
      this.backSuccess = false
      that.getMyOrderListCount()
      getApp().cl_tracker.track('mini_program_view', {
        path: this.nowPages,
        pageName: '我的订单/预约申请',
      })
    },

    //  返回按钮跳转页面
    onUnload(option) {
      if (
        this.back == 'pages/return/details' ||
        this.back == 'pages/order/details' ||
        this.back == 'pages/return/applySuccess' ||
        this.back == 'pages/return/return' ||
        this.back == 'pages/order/reLogistics'
      ) {
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/customer/customer'
          });
        }, 100);
      }
      if (this.back == 'pages/order/submit' && this.skipPaySuccess == true) {
        uni.reLaunch({
          url: '/pages/cart/cart'
        });

      }
      if (this.back == 'pages/order/paySuccess') {
        uni.reLaunch({
          url: '/pages/cart/cart'
        });
      }

    },
    methods: {
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){},
      // 跳转首页
      handleToHomePage(){
        uni.reLaunch({
          url: '/pages/home/home'
        });
      },
      skipSale() {
        let {
          listPath,
          tsActId,
          name
        } = uni.getStorageSync('TsInfo')
        uni.reLaunch({
          url: listPath
        })
        this.trackClickBar()
      },
      trackClickBar() {
        let {
          tsActId,
          name
        } = uni.getStorageSync('TsInfo');
        let params = {
          "c_pageName": "我的订单",
          "c_campaignID": tsActId,
          "c_campaignName": name
        }
        getApp().commonClTrack('c_ebmp_home_member_campaign_click_bar', params);
      },
      async getOrderInfo() {
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
        const json = await api.getOrderInfo({
            header: {
              jwt: customerInfo.jwt
            }
          },
          this.submitOrderId
        );
        if (json.code === 1000) {
          if (json.data.status == 'WAIT_SELLER_SEND_GOODS') {
            uni.navigateTo({
              url: '/pages/order/paySuccess?orderNo=' + this.submitOrderId
            });
            this.submitOrderId = ''
          }
        }
      },

      setOrderId(id) {
        this.submitOrderId = id
      },

      endCutdown(index) {
        this.orderList[index].status = 'TRADE_CLOSED_BY_CLOUD'
        this.getMyOrderSale()
      },

      //获取 待支付 待发货 待收货数量
      getMyOrderListCount: async function() {
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
        let arr = []
        if (this.$programSetting.openAppointment) {
          arr = {
            queries: [{
                queryKey: "WAIT_SYSTEM_CONFIRM",
                queryMatch: {
                  status: "WAIT_BUYER_PAY",
                  approveStatus: '0'
                }
              },
              {
                queryKey: "WAIT_BUYER_PAY",
                queryMatch: {
                  status: "WAIT_BUYER_PAY",
                  approveStatus: '1'
                }
              },
              {
                queryKey: "WAIT_SELLER_SEND_GOODS",
                queryMatch: {
                  status: "WAIT_SELLER_SEND_GOODS",
                },
              },
              {
                queryKey: "WAIT_BUYER_CONFIRM_GOODS",
                queryMatch: {
                  status: "WAIT_BUYER_CONFIRM_GOODS",
                },
              },
            ],
            storeId: merchantInfo.cloudMerchantStoreId
          }
        } else {
          arr = {
            queries: [{
                queryKey: "WAIT_BUYER_PAY",
                queryMatch: {
                  status: "WAIT_BUYER_PAY"
                }
              },
              {
                queryKey: "WAIT_SELLER_SEND_GOODS",
                queryMatch: {
                  status: "WAIT_SELLER_SEND_GOODS",
                },
              },
              {
                queryKey: "WAIT_BUYER_CONFIRM_GOODS",
                queryMatch: {
                  status: "WAIT_BUYER_CONFIRM_GOODS",
                },
              },
            ],
            storeId: merchantInfo.cloudMerchantStoreId
          }
        }
        let json = await api.getMyOrderListCount({
          header: {
            jwt: customerInfo.jwt
          },
          method: 'POST',
          query: arr,
        });
        if (json.code = 1000) {
          this.systemConfirmCount = json.data.WAIT_SYSTEM_CONFIRM
          this.pendingPayCount = json.data.WAIT_BUYER_PAY
          this.backrdersCount = json.data.WAIT_SELLER_SEND_GOODS
          this.shippedCount = json.data.WAIT_BUYER_CONFIRM_GOODS
          let dotList = [{
              name: '全部',
            },
            {
              name: '待审核',
              dotNum: this.systemConfirmCount
            },
            {
              name: '待支付',
              dotNum: this.pendingPayCount
            },
            {
              name: '待发货',
              dotNum: this.backrdersCount
            },
            {
              name: '待收货',
              dotNum: this.shippedCount
            },
            {
              name: '已完成',
            },
          ];
          this.$refs.tab.changeList(dotList);
        }
      },
      // 查询订单前10条显示特殊购买
      getMyOrderSale() {
        this.$commonFunction.getTsByUser().then(async (res) => {
          if (!!res) {
            let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
            let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
            let json = await api.getMyOrderList({
              header: {
                jwt: customerInfo.jwt
              },
              query: {
                customer_id: customerInfo.customerId,
                merchant_id: merchantInfo.cloudMerchantId,
                page_no: 1,
                page_size: 10,
                status: 'WAIT_BUYER_PAY'
              }
            });
            if (json.data.code === 1000) {
              let content = json.data.data.content;
              let hasPrivateSaleSku = content.some((item) => (
                item.addition.hasPrivateSaleSku
              ))
              if (!!hasPrivateSaleSku) {
                this.showSale = true
              } else {
                this.showSale = false
              }
            }
          }
        })
      },
      getMyOrder: async function(currentPage, size, refresh, current) {
        let that = this;
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        const parmas = {
          customer_id: customerInfo.customerId,
          merchant_id: merchantInfo.cloudMerchantId,
          page_no: currentPage || 1,
          page_size: size || 5,
          store_id: merchantInfo.cloudMerchantStoreId
        };
        if (that.orderStatus !== '') {
          parmas.status = that.orderStatus;
        }
        if (current == 1 || current == 2) {
          parmas.status = "WAIT_BUYER_PAY"
        }

        if (current == 1 && this.$programSetting.openAppointment) {
          parmas.approve_status = 0;
        } else if (current == 2 && this.$programSetting.openAppointment) {
          parmas.approve_status = 1;
        }

        let json;
        json = await api.getMyOrderList({
          header: {
            jwt: customerInfo.jwt
          },
          query: parmas
        });
        if (json.data.code === 1000) {
          //浅复制
          let content = json.data.data.content;

          //解析每个数组下面的items.skuProperties属性
          for (let i = 0; i < content.length; i++) {
            for (let j = 0; j < content[i].items.length; j++) {
              // 解析字符串为数组
              if (content[i].items[j]['skuProperties']) {
                content[i].items[j].skuProperties = JSON.parse(content[i].items[j]['skuProperties']);
              }
            }
          }

          if (refresh) {
            let testArr = json.data.data.content;
            let newArr = [...new Set(testArr)];

            that.orderList = await that.getOrderItemHDImg(newArr,merchantInfo);
          } else {
            //相当于a.concat(b)
            // that.orderList = [...that.orderList, ...json.data.data.content];
            let testArr = [...that.orderList, ...json.data.data.content];
            let newArr = [...new Set(testArr)];
            that.orderList = await that.getOrderItemHDImg(newArr,merchantInfo);
          }
					
          //  查询已完成订单的发票金额
          for (let i = 0; i < that.orderList.length; i++) {
            const el = that.orderList[i];
						el.isC2bOrder = false;
						//	判断是否是c2b定制订单
						if(el.addition && el.addition.customization && el.addition.customizationImg){
							el.isC2bOrder = true;
						}
            el.invoiceAmount = 0;
            if(el.status == 'TRADE_FINISHED' && el.shipTime!==null){
              if(el.invoiceStatus == 0 || el.invoiceStatus == 4 || el.invoiceStatus == 5){
                el.invoiceAmount = await that.wosaiInvoiceAmount(el.orderId);
              }
            }
            //  判断已完成的订单是否存在全部退款状态
            el.orderItemsRefundStatus = "";
            if(el.status == "TRADE_FINISHED"){
              if(el.refundStatus == 'NO_REFUND'){
                el.orderItemsRefundStatus = 'Completed';
              }else{
                // 查找已触发退款的商品
                const refundArr = el.items.filter(item => item.refundStatus != "NO_REFUND");
                //  Completed已完成 /Refunded 已退款
                el.orderItemsRefundStatus = refundArr.length === el.items.length ? 'Refunded' : 'Completed';
              }
            }
          }
console.log("########  that.orderList", that.orderList)
          let systemInfo = uni.getStorageSync(SYSTEM_INFO);
          let isIos = systemInfo.system.indexOf('iOS')
          that.cancelTime = getApp().globalData.cancelTime * 60;
          that.orderList.forEach(item => {
            let notGiftNum = 0
            item.items.forEach(innerItem => {
              if (innerItem.isGift == 0) {
                notGiftNum += innerItem.qty
              }
            });
            item.notGiftNum = notGiftNum
            if (!!item.planEndTime) {
              if (isIos == 0) {
                item.cuttime = (new Date(item.planEndTime.replace(/-/g, '/')).getTime() - json.header[
                  'x-cloud-server-timestamp']) / 1000
              } else {
                item.cuttime = (new Date(item.planEndTime).getTime() - json.header['x-cloud-server-timestamp']) / 1000;
              }
            } else {
              if (!!item.approveTime) {
                if (isIos == 0) {
                  item.cuttime = this.cancelTime - (json.header['x-cloud-server-timestamp'] - new Date(item
                      .approveTime.replace(/-/g, '/')).getTime()) / 1000
                } else {
                  item.cuttime = this.cancelTime - (json.header['x-cloud-server-timestamp'] - new Date(item
                    .approveTime).getTime()) / 1000
                }
              } else {
                if (isIos == 0) {
                  item.cuttime = this.cancelTime - (json.header['x-cloud-server-timestamp'] - new Date(item
                      .createTime.replace(/-/g, '/')).getTime()) / 1000
                } else {
                  item.cuttime = this.cancelTime - (json.header['x-cloud-server-timestamp'] - new Date(item
                    .createTime).getTime()) / 1000
                }
              }
            }
          })
          that.$forceUpdate()
          that.page_total = json.data.data.totalPage;
          that.totalCount = json.data.data.total;
          setTimeout(() => {
            that.showLoaded = false;
          }, 100)
          if (json.data.data.total === 0) {
            //暂无数据
            that.is_empty = true;
          } else {
            setTimeout(() => {
              that.showLoaded = false;
            }, 100)
            that.is_empty = false;
          }
          that.getRefundOrderCount();
          that.getMyOrderListCount();
          that.$commonSensors.orderPageView(that.orderList, that.tabList[that.currentTab] == "待审核" ? "待支付" : that.tabList[that.currentTab]);
        } else {
          that.handleShowTextToast('网络异常，请稍后重试');
        }
        that.showLoading = false;
      },


      getGoodsStatus: async function() {
        let that = this;
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        let paramsJson = {
          storeId: merchantInfo.cloudMerchantStoreId,
          orderId: item.orderId
        };
        const goodsEvaluateStateJson = await api.goodsEvaluateState({
            header: {
              jwt: customerInfo.jwt
            }
          },
          paramsJson
        );
      },

      //退货退款数量
      getRefundOrderCount: async function() {
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        const parmas = {
          customer_id: customerInfo.customerId,
          statuses: 'WAIT_SELLER_CONFIRM_GOODS,WAIT_BUYER_RETURN_GOODS,WAIT_SELLER_AGREE,DC_RECEIVED'
        };
        const refundsize = await api.getOrderRefundList({
          header: {
            jwt: customerInfo.jwt
          },
          query: parmas
        });
        if (refundsize.code === 1000) {
          this.refundCount = refundsize.data.content.length;
        }
      },
      //退货退款
      getRefundOrder: async function(currentPage, size, refresh) {
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        const parmas = {
          customer_id: customerInfo.customerId,
          page_no: currentPage || 1,
          page_size: size || 5,

        };
        const refundsize = await api.getOrderRefundList({
          header: {
            jwt: customerInfo.jwt
          },
          query: parmas
        });

        if (refundsize.code === 1000) {
          // that.refundCount = refundsize.data.total;

          //浅复制
          let content = refundsize.data.content;
          setTimeout(() => {
            that.showLoaded = false;
          }, 100)
          //解析每个数组下面的items.skuProperties属性
          for (let i = 0; i < content.length; i++) {
            for (let j = 0; j < content[i].items.length; j++) {
              // 解析字符串为数组
              if (content[i].items[j]['skuProperties']) {
                content[i].items[j].skuProperties = JSON.parse(content[i].items[j]['skuProperties']);
              }
            }
          }
          if (refresh) {
            that.orderList = refundsize.data.content;
          } else {
            //相当于a.concat(b)
            that.orderList = [...that.orderList, ...refundsize.data.content];
          }
          that.orderList.map((item) => {
            item.payment = item.refundFee
          })
          that.page_total = refundsize.data.totalPage;
          if (refundsize.data.total === 0) {
            //暂无数据
            that.is_empty = true;
          } else {
            setTimeout(() => {
              that.showLoaded = false;
            }, 100)
            that.is_empty = false;
          }
        } else {
          that.handleShowTextToast('网络异常，请稍后重试');
        }
        that.showLoading = false;
      },

      skipPaySucc(e) {
        var that = this;
        this.skipPaySuccess = e;
      },

      getCurrentTab(cur, evt) {
        this.showLoaded = true;
        this.currentPage = 1;
        this.page_total = 0;
        this.orderList = [];
        let that = this;
        that.isRefundList = 'N';
        that.currentTab = cur;
        // 0 'WAIT_SYSTEM_CONFIRM',
        //  1 'WAIT_BUYER_PAY',
        //   2'WAIT_SELLER_SEND_GOODS',
        //    3'WAIT_BUYER_CONFIRM_GOODS',
        //    4'TRADE_FINISHED',
        //    5'WAIT_EVALUATION'
        uni.setStorageSync('currentTab', that.currentTab)
        if (cur === 0) {
          that.orderStatus = '';
          that.getMyOrder();
        } else if (cur === 1) {
          that.orderStatus = that.orderStatusArr[0];
          that.getMyOrder(1, 5, false, cur);
        } else if (cur === 2) {
          that.orderStatus = that.orderStatusArr[1];
          that.getMyOrder(1, 5, false, cur);
        } else if (cur === 3) {
          that.orderStatus = that.orderStatusArr[2];
          that.getMyOrder();
        } else if (cur === 4) {
          that.orderStatus = that.orderStatusArr[3];
          that.getMyOrder();
        } else if (cur === 5) {
          that.orderStatus = that.orderStatusArr[4];
          that.getMyOrder();
        }
      },
      /**
       * 滑动切换tab
       */
      bindChange(e) {
        let that = this;
        that.currentTab = e.detail.current;
      },

      fromSon(msg, status) {
        // this.showLoaded = true
        if (msg == 3) {
          this.currentTab = 4;
          this.orderStatus = this.orderStatusArr[3]; //4
        }
        if (status == 'WAIT_BUYER_PAY') {
          //兼容一下 待支付取消订单
          this.getMyOrder(1, 100, 1, this.currentTab);
        } else {
          this.getMyOrder(1, 10, 1, this.currentTab);
        }
      },
      // 计算已完成订单的开发票金额
      async wosaiInvoiceAmount(orderNo) {
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        const amount = await api.getwosaiInvoiceAmount({
            header: {
              jwt: customerInfo.jwt
            }
          },
          orderNo
        );
        if (amount.code === 1000 && amount.data && amount.data.invoiceAmount) {
          return amount.data.invoiceAmount;
        }
        return 0;
      },
      /**
       * 查询订单商品的高清大图
       * @param {Object} lists
       * @param {Object} merchantInfo
       */
      async getOrderItemHDImg(lists,merchantInfo){
        const that = this;
        let _lists = JSON.parse(JSON.stringify(lists));
        if(_lists && _lists.length){
          for (let i = 0; i < _lists.length; i++) {
            const el = _lists[i];
            for (let k = 0; k < el.items.length; k++) {
              const it = el.items[k];
              if(it.extendParameters && it.extendParameters.hdlpImageUrl){
                it.skuImageUrl = it.extendParameters.hdlpImageUrl;
              }else{
                // 订单未返回高清大图内容，调用商品详情查询
                const _goodsRes = await that.getDetailsById(merchantInfo, it.itemId)
                if(_goodsRes) it.skuImageUrl = _goodsRes;
              }
            }
          }
        }
        return _lists;
      },
      /**
       * 获取商品详情
       * @param {Object} merchantInfo
       * @param {Object} itemId
       */
      async getDetailsById(merchantInfo, itemId){
        return new Promise(async (resolve, reject)=>{
          const _res = await api.goodsDetail({
              query: {
                merchant_id: merchantInfo.cloudMerchantId,
                store_id: merchantInfo.cloudMerchantStoreId
              }
            },
            itemId
          );
          let _img = "";
          if(_res && _res.code == 1000 && _res.data && _res.data.resources && _res.data.resources.length){
            const _obj = _res.data.resources.find((item)=>item.kind == "hdlp");
            if(_obj && _obj.kind == "hdlp" && _obj.type == "image" && _obj.url) _img = _obj.url;
          }
          resolve(_img)
        })
      },
      /**
       *  获取购物车为你推荐utools数据
       */
      async handleUtoolsCartRecommend(option) {
        let resData;
        if(option && option.utid) {
          //  预览
          resData = await api.getUtoolsJsonP({
            utoolsId: option.utid,
            type:'orderRecommend'
          });
        } else {
          resData = await api.getUtoolsJson({
            type: 'orderRecommend'
          });
        }
        if (resData.success && resData.data) {
          this.cartRecommendUtools = JSON.parse(resData.data);
          //商品
          const _reslists = await this.getCateGoods(this.cartRecommendUtools?.classId || 8066);
          //  购物车商品列表 都是用hdlpImgUrl字段图片
          _reslists.forEach(item=>{
            if(item?.hdlpImgUrl) item.hoverUrl = item.hdlpImgUrl;
          })
          this.utoolsClassGoodsLists = _reslists;
          this.cartRecommendShow = true;
        }
      },
      /**
       * 查询首页商品分类列表
       * @param {Object} class_id 分类id
       * @param {Object} is_sort  是否筛选
       */
      async getCateGoods(class_id, is_sort) {
        try {
          //获取商品
          let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
          let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
          let res = await this.$commonFunction.doSearchGoods(class_id, '', 1, 200, null, '', is_sort, '', '', '', '')
          let cateProductList = res.data.content; // 商品列表
          //sku实时库存查询
          let skuCodeList = [];
          for (let i = 0; i < cateProductList.length; i++) {
            skuCodeList = skuCodeList.concat(cateProductList[i].skuCodes)
          }
          let reset = await api.getAvailableBatchQty({
            method: "POST",
            header: {
              jwt: customerInfo.jwt
            },
            query: skuCodeList
            // query: JSON.stringify(skuCodeList)
          }, merchantInfo.cloudMerchantId);
          // 策略价格
          let goodsQ = null;
          if (reset.msg == "SUCCESS" && reset?.data?.length) {
            goodsQ = reset.data.filter(item => item.availableQty > 0)
          }
          let list = [];
          cateProductList = cateProductList.map(async item => {
            let res = await this.$commonFunction.priceRulesDeal(item.strategies, item.itemmCode)
            if (goodsQ && goodsQ.length) {
              for (let i = 0; i < goodsQ.length; i++) {
                if (item.skuCodes.indexOf(goodsQ[i].skuCode) !== -1 && goodsQ[i].availableQty > 0) {
                  item.frontQty += goodsQ[i].availableQty
                }
              }
            }
            if (res.price !== 0 && item.itemCode == res.itemCode) {
              item.price = res.price
            }
            if (res.rulesArr.length > 0 && item.itemCode == res.itemCode) {
              item.rulesArr = res.rulesArr
            }
            list.push(item)
            item.isShowMainImg = true;
            return item
          })
          return list
        } catch (err) {
          return null
        }
      },
      /**
       * utools加入购物车回调
       * @param {Object} e
       */
      async onAddCart(e) {
        try {
          const {
            data
          } = e.detail
          let that = this
          let merchantInfo = uni.getStorageSync('merchantInfo');
          let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
          let userInfo = uni.getStorageSync(USER_INFO);
          if (!customerInfo && !userInfo) {
            that.registerType = 'cart';
            // that.getUserProfile();
						this.handleShowTextToast("请加入会员")
            return false;
          } else if (!customerInfo && !!userInfo) {
            that.registerType = 'cart';
            // that.$refs.registerWidgetRef.openJoinMemberModal()
						this.handleShowTextToast("请加入会员")
            return false;
          }
          let goodsInfo = await this.getGoodsDetail(merchantInfo, data.itemId)
          if (!goodsInfo || goodsInfo.code != 1000) return this.handleCartToast({
            success: false,
            msg: "加入购物车失败"
          });
          // 加入购物车
          const cartRes = await this.$commonFunction.buildProductsAddCart({
            price: goodsInfo.data.skus[0].price,
        		itemId: goodsInfo.data.itemId,
            valueId: goodsInfo.data.frontProperties[0].valueId,
            itemCode: goodsInfo.data.itemId,
            itemName: goodsInfo.data.itemName,
            qty: 1,
            skuCode: goodsInfo.data.skus[0].skuCode,
            skuId: goodsInfo.data.skus[0].skuId,
          });
          //  加入购物车提示
          this.handleCartToast(cartRes);
        } catch (e) {
          this.handleCartToast({
            success: false,
            msg: "加入购物车失败"
          });
        }
      },
			/**
			 * 加购提示
			 * @param {Object} obj
			 */
			async handleCartToast(obj) {
				const _arr = ['您动作太快，请慢点哟～', '网络状态不佳，请重试'];
				if(obj.msg && _arr.includes(obj.msg)){
					this.handleShowTextToast(obj.msg)
				}else if(obj.data && obj.data.msg && obj.data.type === 'showToast'){
					this.handleShowTextToast(obj.data.msg)
				}else{
					if (obj?.success) this.getCartList();
					this.cartMessage = obj?.msg || "加入购物车失败";
					this.cartStatus = obj?.success || false;
					this.showCartMsg = true;
					setTimeout(() => {
					  this.showCartMsg = false;
					}, 3000);
				}
			},
      //商品和购物车有数埋点2
      onTriggerComponent(e) {
        try{
          const {item, type, trackData} = e.detail.data;
          const _typeArr = ["itemClick", "addCartClick"];
          if(item && _typeArr.includes(type)) this.$refs.shopCart.srTracking(item,type);
        }catch(e){
        }
      },
      async setPanel(d = null) { },
      /**
       * 获取商品详情
       * @param {Object} merchantInfo
       * @param {Object} itemId
       */
      async getGoodsDetail(merchantInfo,itemId) {
      	return await api.goodsDetail({
      			query: {
      				merchant_id: merchantInfo.cloudMerchantId,
      				store_id: merchantInfo.cloudMerchantStoreId
      			}
      		},
      		itemId
      	);
      },
    },

    //加载更多
    onReachBottom() {
      let that = this;
      that.showLoading = true;
      //判断总页数是否大于翻页数
      // debugger
      if (that.page_total > that.currentPage) {
        //防止重复加载
        if (that.preventRepeatReuqest) {
          return true;
        }
        that.preventRepeatReuqest = true;
        that.currentPage++;
        if (this.currentTab == 0) {
          // 所有订单类型
          that.getMyOrder(that.currentPage);
        } else if (this.currentTab == 1) {
          // 未付款订单类型
          that.orderStatus = that.$programSetting.openAppointment ? that.orderStatusArr[0] : that.orderStatusArr[1];
          that.getMyOrder(that.currentPage);
        } else if (this.currentTab == 2) {
          // 待发货订单类型
          that.orderStatus = that.orderStatusArr[1];
          that.getMyOrder(that.currentPage);
        } else if (this.currentTab == 3) {
          // 待发货订单类型
          that.orderStatus = that.orderStatusArr[2];
          that.getMyOrder(that.currentPage);
        } else if (this.currentTab === 4) {
          that.orderStatus = that.orderStatusArr[3];
          that.getMyOrder(that.currentPage);
        } else if (this.currentTab === 5) {
          that.orderStatus = that.orderStatusArr[4];
          that.getMyOrder(that.currentPage);
        }
        that.preventRepeatReuqest = false;
      } else {
        that.showLoading = false;
      }
    },
    events: {
      refreshOrderList(msg) {
        if (msg == 3) {
          this.currentTab = 4;
          this.orderStatus = this.orderStatusArr[3]; //4
        }
        this.getMyOrder(1, 10, 1);
      }
    },

    onPullDownRefresh() {
      uni.showNavigationBarLoading(); //在当前页面显示导航条加载动画
      this.orderList = [];
      this.currentPage = 1;
      this.getMyOrder();
      setTimeout(function() {
        uni.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
        uni.stopPullDownRefresh(); //停止下拉动作
      }, 2000);
    }
  };
</script>
<style lang="less">
  .ts-entrance {
    position: fixed;
    bottom: 0;
    z-index: 2;
    width: 100%;

    .fix-iphonex-button {
      bottom: 0 !important;
      height: 40rpx;
      background: #fff;
    }
  }

  .swiper-tab-pd {
    background: #fff;
    position: fixed;
    // top: 0;
    z-index: 2;
    width: 100%;
  }

  .swiper-item-box {
    margin-top: 86rpx;
  }

  .swiper-item-box2 {
    margin-top: 136rpx;
  }

  .swiper-tab {
    height: 80rpx;
  }

  .swiper-tab-order.active {
    color: #ff4856;
    border-bottom: 5rpx solid #ff4856;
  }

  .reveiveMoney {
    display: none;
  }

  .rma_state {
    height: 36rpx;
    line-height: 46rpx;
  }

  .info-container {
    padding: 10px 0;
    color: #999;
    font-size: 10px;
    background-color: #efefef;
    text-align: center;
  }

  .info-container em {
    font-size: 26rpx;
    text-decoration: underline;
    color: #444;
  }

  .icon-cuowu1 {
    z-index: 1001;
  }

  .empty_cart {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    margin: 278rpx 0 132.96rpx;
    .icon-xl {
      width: 108.38rpx;
      height: 80rpx;
      display: block;
      margin: 0 auto;
    }
    .shop_btn {
      width: 100%;
      margin-top: 80rpx;
    }
    .get_store {
      margin: 80rpx auto 0;
      width: 176rpx;
      height: 80rpx;
      line-height: 76rpx;
      border-radius: 48rpx 16rpx 48rpx 48rpx;
      color: #fff;
      font-family: NotoSansSC-Medium;
      border: 1px solid #CB171A;
      font-size: 28rpx;
      background-color: #CB171A;
      text-align: center;
    }
  }
  .empty_cart_text {
    font-family: NotoSansSC-Regular;
    color: #000000;
    font-size: 14px;
    line-height: 24px;
    margin-top: 40rpx;
    text-align: center;
  }
  .empty_line{
    width:750rpx;
    height:12rpx;
  }
  .bottom_line{
    position: fixed;

  }
</style>
